package com.UKIT.airtickets.Activities.fragments

import TicketAdapter
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.core.view.children
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.UKIT.airtickets.DB.AppDatabase
import com.UKIT.airtickets.R
import com.UKIT.airtickets.Service.Handlers.FavouritesHandler
import com.UKIT.airtickets.Service.Tikets
import com.UKIT.airtickets.databinding.FragmentFavouritesBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class FavouritesFragment : Fragment(), TicketAdapter.OnFavoriteClickListener {

    private lateinit var adapter: TicketAdapter
    private lateinit var binding: FragmentFavouritesBinding
    private lateinit var favouritesHandler: FavouritesHandler

    override fun onAttach(context: Context) {
        super.onAttach(context)
        favouritesHandler = FavouritesHandler(context)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentFavouritesBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        adapter = TicketAdapter(this, AppDatabase.getDatabase(requireContext()).userFavoriteDao())
        binding.favouriteTickets.adapter = adapter
        binding.favouriteTickets.layoutManager = LinearLayoutManager(requireContext())
        CoroutineScope(Dispatchers.IO).launch {
            favouritesHandler.updateFavoritesList(adapter, binding.linearLayout3.findViewById(R.id.total_amount))
        }
        binding.linearLayout3.findViewById<Button>(R.id.pay_button).setOnClickListener{
            CoroutineScope(Dispatchers.IO).launch {
                favouritesHandler.getFavoritesFromDatabase().forEach{
                    favouritesHandler.toggleFavoriteStatus(it, adapter)
                }
                CoroutineScope(Dispatchers.Main).launch {
                    adapter.notifyDataSetChanged()
                    Toast.makeText(requireContext(),"Оплата прошла успешно", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onFavoriteClick(ticket: Tikets) {
        CoroutineScope(Dispatchers.IO).launch {
            favouritesHandler.toggleFavoriteStatus(ticket, adapter)
        }
    }
}
